/**
 *
 * @description: 用户路由
 * @author: junyong.hong
 * @createTime: 2018/3/11
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = require('../models/User');
require('../util/util.js');

mongoose.connect('mongodb://127.0.0.1:27017/db_demo');

// 连接成功
mongoose.connection.on('connected', function () {
  console.log('MongoDB connected success.');
});

// 连接失败
mongoose.connection.on('error', function () {
  console.log('MongoDB connected fail.');
});

// 断开连接
mongoose.connection.on('disconnected', function () {
  console.log('MongoDB connected disconnected.');
});

/**
 * 用户登录
 */
router.post('/login', function (req, res, next) {
  var param = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  User.findOne(param, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      });
    } else {
      if (doc) {
        // 用户信息存到cookie中
        res.cookie('userId', doc.userId, {
          // 放到服务器的根目录
          path: '/',
          // 保存一个小时
          maxAge: 1000*600*60
        });
        res.cookie('userName', doc.userName, {
          // 放到服务器的根目录
          path: '/',
          // 保存一个小时
          maxAge: 1000*600*60
        });
        // 用户信息存到session中
        // req.session.user = doc;

        res.json({
          status: '0',
          msg: '',
          result: {
            userName: doc.userName,
          }
        })
      } else {
        res.json({
          status: '1',
          msg: '帐号密码错误',
          result: ''
        })
      }
    }
  })

});

/**
 * 用户退出
 */
router.post('/logout', function (req, res, next) {
  res.cookie('userId', '', {
    path: '/',
    maxAge: -1
  });
  res.json({
    status: '0',
    msg: '',
    result: ''
  })
});

/**
 * 校验登录
 */
router.get("/checkLogin", function (req, res, next) {
  if (req.cookies.userId) {
    res.json({
      status: '0',
      msg: '',
      result: req.cookies.userName || ''
    });
  } else {
    res.json({
      status: '1',
      msg: '未登录',
      result: ''
    });
  }
});

/**
 * 查询当前用户的购物车数据
 */
router.get('/cartList', function (req, res, next) {
  var userId = req.cookies.userId;
  User.findOne({userId: userId}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (doc) {
        res.json({
          status: '0',
          msg: '',
          result: doc.cartList
        });
      }
    }
  })

});


/**
 * 购物车删除
 */
router.post('/cartDel', function (req, res, next) {
  var userId = req.cookies.userId, productId = req.body.productId;
  User.update({
    userId: userId
  }, {
    // 删除购物车中cartList数组中指定的productId
    $pull: {
      'cartList': {
        'productId': productId
      }
    }
  }, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: '',
        result: 'success'
      });
    }
  })
});

/**
 * 修改商品数量
 */
router.post('/cartEdit', function (req, res, next) {
  var userId = req.cookies.userId,
      productId = req.body.productId,
      productNum = req.body.productNum,
      checked = req.body.checked;
  User.update({
    'userId': userId,
    'cartList.productId': productId
  },{
    'cartList.$.productNum': productNum,
    'cartList.$.checked': checked
  },function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: '',
        result: 'suc'
      })
    }
  })
});

/**
 * 全选、反选
 */
router.post('/editCheckAll', function (req, res, next) {
  var userId = req.cookies.userId,
      checkAll = req.body.checkAll ? '1' : '0';
  // 拿到当前的用户
  User.findOne({userId:userId}, function (err, user) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      if(user) {
        // 遍历cartList
        user.cartList.forEach((item) => {
          item.checked = checkAll;
        });
        // 保存
        user.save(function (err1, doc) {
          if(err1) {
            res.json({
              status: '1',
              msg: err1.message,
              result: ''
            });
          } else {
            res.json({
              status: '0',
              msg: '',
              result: 'suc'
            });
          }
        })
      }
    }
  })

});


/**
 * 查询用户地址接口
 */
router.get('/addressList', function (req, res, next) {
  var userId = req.cookies.userId;
  User.findOne({userId: userId}, function (err,doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: '',
        result: doc.addressList
      });
    }
  })
});

/**
 * 设置默认地址
 */
router.post('/setDefault', function (req, res, next) {
  var userId = req.cookies.userId,
      addressId = req.body.addressId;

  // 如果地址的id为空
  if(!addressId) {
    res.json({
      status: '1003',
      msg: 'addressId is null',
      result: ''
    });
  } else {
    User.findOne({userId: userId}, function (err, doc) {
      if(err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        });
      } else {
        var addressList = doc.addressList;
        // 对数据进行遍历
        addressList.forEach((item) => {
          // 如果遍历出来的id等于传过来的id相等，那么isDefault为true
          if(item.addressId == addressId ) {
            item.isDefault = true
          } else {
            item.isDefault = false;
          }
        });

        // 对数据进行保存
        doc.save(function (err1, doc1) {
          if (err1) {
            res.json({
              status: '1',
              msg: err1.message,
              result: ''
            });
          } else {
            res.json({
              status: '0',
              msg: '',
              result: ''
            })
          }
        })

      }
    })
  }
});

/**
 * 删除地址
 */
router.post('/delAddress', function (req, res, next) {
  var userId = req.cookies.userId,
      addressId = req.body.addressId;

  User.update({
    userId: userId
  },{
    // 删除addressList数组中指定的addressId
    $pull: {
      'addressList': {
        'addressId': addressId
      }
    }
  }, function (err, doc) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      res.json({
        status: '0',
        msg: '',
        result: ''
      })
    }
  });
});

/**
 * 创建订单
 */
router.post('/payMent', function (req, res, next) {
  var userId = req.cookies.userId,
      addressId = req.body.addressId,
      orderTotal = req.body.orderTotal;

  User.findOne({userId: userId}, function (err, doc) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      var address = '', goodsList = [];
      // 获取当前用户的地址信息
      doc.addressList.forEach((item) => {
        if (addressId == item.addressId) {
          address = item;
        }
      });
      // 获取用户购物车的购买商品
      doc.cartList.filter((item) => {
        if(item.checked == '1') {
          goodsList.push(item);
        }
      });

      // 平台编码
      var plateform = '0527';
      var r1 = Math.floor(Math.random() * 10);
      var r2 = Math.floor(Math.random() * 10);

      var sysDate = new Date().Format('yyyyMMddhhmmss');
      // 创建时间
      var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
      // 订单id
      var orderId = plateform + r1 + sysDate + r2;

      var order = {
        // 订单id
        orderId: orderId,
        // 订单总金额
        orderTotal: orderTotal,
        // 地址
        addressInfo: address,
        // 商品列表
        goodsList: goodsList,
        // 订单状态
        orderStatus: '1',
        // 创建时间
        createDate: createDate
      };

      doc.orderList.push(order);

      doc.save(function (err1, doc1) {
        if(err1) {
          res.json({
            status: '1',
            msg: err1.message,
            result: ''
          });
        } else {
          res.json({
            status: '0',
            msg: '',
            result: {
              orderId: order.orderId,
              orderTotal: order.orderTotal
            }
          })
        }
      });
    }
  })

});

/**
 * 根据订单id查询订单信息
 */
router.get('/orderDetail', function (req, res, next) {
  var userId = req.cookies.userId,
      orderId = req.param('orderId');
  User.findOne({userId: userId}, function (err, userInfo) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      });
    } else {
      var orderList = userInfo.orderList;
      //订单里有内容
      if(orderList.length > 0){
        var orderTotal = 0;
        orderList.forEach((item) => {
          if(item.orderId == orderId) {
            orderTotal = item.orderTotal;
          }
        });

        // 订单的金额大于0
        if (orderTotal > 0) {
          res.json({
            status: '0',
            msg: '',
            result: {
              orderId: orderId,
              orderTotal: orderTotal
            }
          });
        } else {
          res.json({
            status: '120002',
            msg: '无此订单',
            result: ''
          });
        }
      } else {
        res.json({
          status: '120001',
          msg: '当前用户未创建订单',
          result: ''
        });
      }
    }
  })
});

/**
 * 获取购物车数量
 */
router.get('/getCartCount', function (req, res, next) {
  if(req.cookies && req.cookies.userId) {
    var userId = req.cookies.userId;
    User.findOne({userId: userId}, function (err, doc) {
      if(err) {
        res.json({
          status: '1',
          msg: err.message,
          result: ''
        })
      } else {
        // 购物车列表
        var cartList = doc.cartList;
        // 数量
        var cartCount = 0;
        // 遍历购物车
        cartList.map(function (item) {
          cartCount += parseInt(item.productNum);
        });
        res.json({
          status: '0',
          msg: '',
          result: cartCount
        })
      }
    })
  }

});

module.exports = router;
